/*
 * @Author: 肖思汗 
 * @Date: 2025-06-02 13:35:43 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-11-11 14:05:18
 */
import { autorun } from "mobx";
import FabricCanvas from "../myFabric/FabricCanvas";
import FabricImg from "../myFabric/FabricImg";
import FabricText from "../myFabric/FabricText";
import brContorls from "../myFabric/brContorls";
import tlContorls from "../myFabric/tlContorls";
import trContorls from "../myFabric/trContorls";
import designerStore from "./designerStore";
// 图片地址缓存
// import uploadOssClient from "src/api/uploadOssClient";
import Taro, { Canvas } from "@tarojs/taro";
import cloneDeep from "lodash/cloneDeep";
import goodsUtils from "src/utils/goodsUtils";
import utils from "src/utils/utils";
import Transition from "../myFabric/Transition";
import fontManage from "../myFabric/fontManage";

import designerHistory from "./designerHistory";
// 移除对不存在模块的引用
// import textureManager from "../textureManager";
// import syncFlowerPatternStore from '../SyncFlowerPattern/syncFlowerPatternStore';
// import textModelStore from '../TextModel/textModelStore';

import { ActiveSelection, Circle as fabricCircle, Path as fabricPath, Polygon as fabricPolygon, Rect as fabricRact } from "fabric";
import { set } from "lodash";
import Api from "src/api/Api";
import { FabricJSON } from "types/type";

import closePNG from "./img/close.png";
import editorPNG from "./img/editor.png";
import mtrPNG from "./img/mtr.png";
import indexStore from "../index/indexStore";

// 2d 编辑器对象 本程序只考虑h5和微信小程序
class DesignerRender extends FabricCanvas {

    constructor() {
        super();
        // console.log("designerRender", this);
        global.designerRender = this;
    }


    allowTouchScrolling: boolean = true;

    // 画布上的canvas
    canvas
    canvasCtx;

    // 主canvas
    mainCanvas: any = null;

    // 触摸结束时如果没有选中对象是否需要取消选中
    discardWidthTouchend: boolean = true;

    async init(canvas: Canvas) {
        canvas.width = 1024;
        canvas.height = 1024;
        this.canvas = canvas;


        this.canvasCtx = this.canvas.getContext('2d');


        const canvasElement = document.createElement('canvas');
        canvasElement.width = 1024;
        canvasElement.height = 1024;
        this.mainCanvas = canvasElement;

        super.init(this.mainCanvas);

        const contorlWidth = 50;

        // 创建br控制器的图标
        const brImage = new Image();
        brImage.src = mtrPNG;
        brImage.onload = () => {
            const img = new FabricImg(brImage, {});
            const { width, height } = brImage;
            const maxSide = Math.max(width, height);
            img.set({
                scaleX: contorlWidth / maxSide,
                scaleY: contorlWidth / maxSide,
            });
            brContorls.icon = img;
        };

        // 初始化离屏画布和上下文
        this.initCanvas();

        //创建tl控制器图标
        const tlImage = new Image();
        tlImage.src = closePNG;
        tlImage.onload = () => {
            const img = new FabricImg(tlImage, {});
            const { width, height } = tlImage;
            const maxSide = Math.max(width, height);
            img.set({
                scaleX: contorlWidth / maxSide,
                scaleY: contorlWidth / maxSide,
            });
            tlContorls.icon = img;
        };

        //创建tr控制器图标
        const trImage = new Image();
        trImage.src = editorPNG;
        trImage.onload = () => {
            const img = new FabricImg(trImage, {});
            const { width, height } = trImage;
            const maxSide = Math.max(width, height);
            img.set({
                scaleX: contorlWidth / maxSide,
                scaleY: contorlWidth / maxSide,
            });
            trContorls.icon = img;
        };
    }

    designMark;//设计区域的遮罩图

    oulineMark;//轮廓区域的遮罩图

    backgroundImage;// 局部印的实物背景图
    async setBackgroundImage(backgroundImage: string | undefined): Promise<void> {
        this.backgroundImage = backgroundImage ? await this.createImage(backgroundImage) : undefined;
    }

    // 设置背景元素
    async setBackground(imageUrl: string): Promise<void> {
        const image = await this.createImage(imageUrl);
        // 创建一个背景图片对象
        const bgImage = new FabricImg(image, {
            selectable: false,
            evented: false,
            left: 0,
            top: 0,
            scaleX: 1024 / image.width,
            scaleY: 1024 / image.height
        });
        // 添加自定义属性标记为背景
        (bgImage as any).isBackground = true;

        // 清除现有的背景
        this.remove(...this.getObjects().filter(obj => (obj as any).isBackground));

        // 添加新背景
        this.add(bgImage);

        // 记录历史操作
        const json = this.toJSON();
        designerHistory.recordHistory(json);

        // 请求重新渲染
        this.requestRenderAll();
    }

    // 设计区域轮廓图会在设计区域绘制完成后,使用这个遮罩以 0.8的透明度遮住设计内容
    oulineMarkCanvas = null;
    oulineMarkctx = null;

    // 初始化画布和上下文
    initCanvas() {
        /* 暂时注释掉离屏画布相关代码以避免TypeScript错误
        // H5环境下尝试创建离屏画布
        this.oulineMarkCanvas = Taro.createOffscreenCanvas({
            type: '2d',
            width: 1024,
            height: 1024,
        });
        // 安全地获取上下文
        if (this.oulineMarkCanvas && typeof this.oulineMarkCanvas.getContext === 'function') {
    this.oulineMarkctx = this.oulineMarkCanvas.getContext('2d') as any;
        } else {
            console.warn('无法获取画布上下文，将使用替代方案');
            // 创建一个模拟的上下文对象
            this.oulineMarkctx = this.createMockContext();
        }
        */
        // 直接使用模拟上下文
        // this.oulineMarkctx = 
    }

    outlineDash;//板片虚线图
    printlineDash;//局部印的打印区域虚线图

    // 视口动画对象
    viewTransition = (() => {
        const viewTransition = new Transition({ scale: 1, x: 0, y: 0 });
        viewTransition.setDuration(500);
        viewTransition.onChange(({ scale, x, y }) => {
            this.setViewportTransform([scale, 0, 0, scale, x, y]);
            this.requestRenderAll();
        });
        return viewTransition;
    })();

    // 初始化所有部位的遮罩对象
    async initFabricMarkMap(designMarkUrl, oulineMarkUrl, outlineDashUrl, printlineDash) {
        while (!this.mainCanvas) {
            await new Promise(resolve => setTimeout(resolve, 30));
        }
        this.designMark = designMarkUrl ? await this.createImage(designMarkUrl) : undefined;
        this.oulineMark = oulineMarkUrl ? await this.createImage(oulineMarkUrl) : undefined;
        this.outlineDash = outlineDashUrl ? await this.createImage(outlineDashUrl) : undefined;
        this.printlineDash = printlineDash ? await this.createImage(printlineDash) : undefined;
        this.requestRenderAll();
    }

    // 绘制背景
    renderBackground(ctx = this.ctx) {
        if (!ctx) {
            return;
        }
        //局部印是以实物衣服作为底图
        if (this.backgroundImage) {
            ctx.save();
            // ctx.setTransform(1, 0, 0, 1, 0, 0);

            ctx.transform(...this.viewportTransform);
            ctx.globalCompositeOperation = "destination-over";
            if (this.backgroundImage.width) {
                ctx.drawImage(this.backgroundImage, 0, 0, 1024, 1024);
            }
            ctx.restore();
            // 满版印如果有背颜色就绘制轮廓+颜色生成背景
        } else if (this.background && this.oulineMark) {
            /* 暂时注释掉可能报错的代码
            this.oulineMarkctx.globalCompositeOperation = "copy";
            this.oulineMarkctx.fillStyle = this.background;
            this.oulineMarkctx.fillRect(0, 0, 1024, 1024);
            //衣服轮廓
            if (this.oulineMark) {
                this.oulineMarkctx.globalCompositeOperation = "destination-out";
                if (this.oulineMark.width) {
                    this.oulineMarkctx.drawImage(this.oulineMark, 0, 0, 1024, 1024);
                }
            }
            ctx.save();
            // ctx.setTransform(1, 0, 0, 1, 0, 0);
     
             ctx.transform(...this.viewportTransform);
            ctx.globalCompositeOperation = "destination-over";
            ctx.drawImage(this.oulineMarkCanvas, 0, 0, 1024, 1024);
            ctx.restore();
            */

        }


    }

    //渲染
    renderAll(ctx = this.ctx) {
        if (!ctx) {
            return;
        }
        ctx.imageSmoothingEnabled = true;
        this.dispatchEvent({
            type: 'before:render',
            ctx
        });


        ctx.transform(1, 0, 0, 1, 0, 0);
        ctx.clearRect(0, 0, this.width, this.height);

        ctx.save();
        // 一次性应用视口变换以进行所有渲染过程
        ctx.transform(...this.viewportTransform);

        for (let obj of this._objects) {
            obj.render(ctx);
        }
        ctx.restore();

        // 绘制设置图的遮罩
        if (this.designMark) {
            ctx.save();
            ctx.globalCompositeOperation = "destination-out";
            ctx.globalAlpha = this._activeObject ? 0.9 : 1.0;
            ctx.transform(...this.viewportTransform);
            if (this.designMark.width) {
                ctx.drawImage(this.designMark, 0, 0, 1024, 1024);
            }
            ctx.restore();
        }

        this.renderBackground(ctx);

        //局部印是以实物衣服作为底图
        if (this.backgroundImage) {

            if (this._activeObject) {
                ctx.save();
                ctx.globalCompositeOperation = "source-over";

                ctx.transform(...this.viewportTransform);
                if (this.printlineDash.width) {
                    ctx.drawImage(this.printlineDash, 0, 0, 1024, 1024);
                }
                ctx.restore();
            }

        } else if (this.outlineDash) {
            //绘制轮廓虚线图
            ctx.save();
            ctx.transform(...this.viewportTransform);
            ctx.globalCompositeOperation = "source-over";
            if (this.outlineDash.width) {
                ctx.drawImage(this.outlineDash, 0, 0, 1024, 1024);
            }
            ctx.restore();
        }

        if (this._activeObject) {
            this._activeObject.setCoords();
            this._activeObject._renderControls(ctx);
        }

        // if (path) {
        //     path._set('canvas', this);
        //     // 需要设置一些变量
        //     // todo 迁移到较新的版本
        //     path.shouldCache();
        //     path._transformDone = true;
        //     (path).renderCache({ forClipping: true });
        //     this.drawClipPathOnCanvas(ctx, path);
        // }
        this.dispatchEvent({
            type: 'after:render',
            ctx
        });
    }

    imgMap = new Map();

    // 创建图片
    async createImage(src: string) {
        while (!this.mainCanvas) {
            await new Promise(resolve => setTimeout(resolve, 30));
        }

        // 有就直接返回
        if (this.imgMap.has(src)) {
            return this.imgMap.get(src);
        }

        Taro.showLoading({ title: '图片加载中' });

        // 创建图片实例
        const image = new Image();
        await new Promise<void>(async (resolve) => {

            // 超时控制
            const timer = setTimeout(() => {
                image.src = ''; // 中止加载
                console.warn(`图片加载超时:${src}`);
                resolve();
            }, 15000);

            image.onload = () => {
                this.imgMap.set(src, image);
                clearTimeout(timer);
                resolve();
            }
            image.onerror = () => {
                console.warn(`图片加载失败:${src}`);
                Taro.showToast({
                    title: '图片加载失败',
                    duration: 2000
                });
                resolve();
            }

            const newSrc = utils.ossSuffix(src, 1024);
            image.src = newSrc;
        });
        Taro.hideLoading();
        return image;
    }

    // 预加载图片
    async preloadImg(src) {
        const start = new Date().valueOf()
        const ctx = designerRender.getContext();
        const img = await designerRender.createImage(src);
        if (img.width) {
            ctx.drawImage(img, 0, 0, 1, 1);
        }

    }

    // 给图片设置遮罩
    setImageMask(url?: string, maskData?: any) {
        const activeObject = this.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            activeObject.clipSvgUrl = url;
            if (maskData) {
                const minScale = Math.min(activeObject.width! / maskData.width!, activeObject.height! / maskData.height!);
                maskData.left = minScale * maskData.width! / -2;
                maskData.top = minScale * maskData.height! / -2;
                maskData.scaleX = minScale;
                maskData.scaleY = minScale;
                if (["path", "Path"].includes(maskData.type)) {
                    activeObject.clipPath = new fabricPath("").set(maskData);
                } else if (["polygon", "Polygon"].includes(maskData.type)) {
                    activeObject.clipPath = new fabricPolygon().set(maskData);
                } else if (["circle", "Circle"].includes(maskData.type)) {
                    activeObject.clipPath = new fabricCircle().set(maskData);
                } else if (["rect", "Rect"].includes(maskData.type)) {
                    activeObject.clipPath = new fabricRact().set(maskData);
                }
                if (activeObject.clipPath) {
                    activeObject.clipPath.set({
                        originX: 'center',
                        originY: 'center',
                    });
                }

            } else {
                activeObject.clipPath = undefined;
            }

            // 选了遮罩就去编辑裁剪
            // cropModelStore和cropEditor不存在，注释掉相关调用
            /*
            cropModelStore.setShow(true);
            cropEditor.setImage({
                url: activeObject.getSrc(),
                cropX: activeObject.cropX,
                cropY: activeObject.cropY,
                width: activeObject.width,
                height: activeObject.height,
                clipPath: activeObject.clipPath ? activeObject.clipPath.toJSON() : undefined,
            });
            */

            activeObject.set({
                dirty: true
            });
        }
        this.requestRenderAll();



    }

    //添加图片 // select 添加完成后选中
    async addImg(src: string, select = true): Promise<FabricImg> {

        const image = await this.createImage(utils.ossSuffix(src, 1024));
        const img = new FabricImg(image, {});
        const { width, height } = img;
        const maxSide = Math.max(width, height);
        const printRact = await this.get_print_area();
        img.set({
            src: src,
            left: printRact.left + (printRact.width / 2),
            top: printRact.top + (printRact.height / 2),
            scaleX: Math.min(printRact.width, printRact.height, 1024) / maxSide,
            scaleY: Math.min(printRact.width, printRact.height, 1024) / maxSide,
        });

        const objs = this.getObjects();
        if (objs.length) {
            objs.map((obj) => {
                if (obj.left === img.left) {
                    img.left += 20;
                }
                if (obj.top === img.top) {
                    img.top += 20;
                }
            });
        }
        this.add(img);
        designerRender.recordHistory();
        if (select) {
            this.setActiveObject(img);
        }
        this.requestRenderAll();
        return img;
    }

    //添加文本
    async addText(text: string, options?: any): Promise<FabricText> {
        const fabricText = new FabricText(text, { ...options, canvas: this });
        const printRact = await this.get_print_area();
        fabricText.set({
            id: new Date().valueOf(),
            left: printRact.left + (printRact.width / 2),
            top: printRact.top + (printRact.height / 2),
            fontSize: 100,
            bendDegree: 0
        });

        fontManage.loadFont([fabricText.fontFamily]);
        fabricText.setCoords();

        const objs = this.getObjects();
        if (objs.length) {
            objs.map((obj) => {
                if (obj.left === fabricText.left) {
                    fabricText.left += 20;
                }
                if (obj.top === fabricText.top) {
                    fabricText.top += 20;
                }
            });
        }

        fabricText._updatePath();
        this.add(fabricText);
        this.recordHistory();
        this.setActiveObject(fabricText);
        this.requestRenderAll();
        return fabricText;
    }

    //放大
    amplify() {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            activeObject.scaleX *= 1.1;
            activeObject.scaleY *= 1.1;
            this.recordHistory();
            this.requestRenderAll();
        }
    }


    // 缩小
    reduce() {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            activeObject.scaleX *= 0.9;
            activeObject.scaleY *= 0.9;
            this.recordHistory();
            this.requestRenderAll();
        }
    }

    // 添加间距
    addSpacing() {
        const activeObject = this.getActiveObject();
        if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
            activeObject.set("charSpacing", activeObject.charSpacing + 100);
            this.recordHistory();
            this.requestRenderAll();
        }
    }

    // 减少间距
    subSpacing() {
        const activeObject = this.getActiveObject();
        if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
            activeObject.set("charSpacing", Math.max(-1000, activeObject.charSpacing - 100));
            this.recordHistory();
            this.requestRenderAll();
        }
    }

    // 通过id 修改对象的属性
    modifyObjectById(id, option: any) {
        const activeObject = this.getObjectById(id);
        if (activeObject) {
            activeObject.set(option);
            this.requestRenderAll();
        }
    }

    // 通过id 增加字号 // 增量
    addFontSize(id: string, increment: number) {
        const activeObject = this.getObjectById(id);
        this.modifyObjectById(id, { fontSize: (activeObject as FabricText).fontSize + increment });
    }
    

    //修改当前选中文本对象
    modifyText(key: string, value: any): void {
        const activeObject = this.getActiveObject();
        if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
            activeObject.set(key, value);
            this.recordHistory();
            this.requestRenderAll();
        }
    }

    // 下载当前画布上的内容
    async download() {
        if (this.mainCanvas) {

            // 微信小程序使用
            const res = await Taro.canvasToTempFilePath({
                canvas: this.canvas, // 直接传递节点对象
                fileType: 'png',
                quality: 1
            });
            // 检查权限
            const { authSetting } = await Taro.getSetting();
            if (!authSetting['scope.writePhotosAlbum']) {

                const { errMsg } = await Taro.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() { /* 授权成功回调 */ },
                    fail() { /* 授权失败回调 */ },
                    complete() { /* 调用结束回调 */ }
                });

                if (errMsg) {
                    Taro.showModal({
                        title: '提示',
                        content: '需要您授权保存到相册',
                        success: (res) => {
                            if (res.confirm) {
                                // 打开设置页面让用户手动开启权限
                                Taro.openSetting({
                                    success: (settingRes) => { }
                                });
                            }
                        }
                    });
                }
            }

            //保存到手机相册
            await Taro.saveImageToPhotosAlbum({
                filePath: res.tempFilePath
            });

            Taro.showToast({
                title: '下载成功'
            });
        }
    }

    // 复制
    async copy(): Promise<void> {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            if (activeObject.type === 'image') {
                const img = await this.addImg(activeObject.src);
                const { ...objectJson } = activeObject.toObject();
                objectJson.left += 20;
                objectJson.top += 20;
                img.set(objectJson);
                this.setActiveObject(img);
            } else if (['i-text', "IText", 'text'].includes(activeObject.type)) {
                const { text, ...objectJson } = activeObject.toObject();
                const textObj = await this.addText(activeObject.text);
                objectJson.left += 20;
                objectJson.top += 20;
                textObj.set(objectJson);
                this.setActiveObject(textObj);
            }
        }
    }

    // 添加对象
    async addObject(object: any): Promise<void> {
        if (object) {
            if (object.type === 'image') {
                const img = await this.addImg(object.src);
                const { ...objectJson } = object.toObject();
                objectJson.left += 20;
                objectJson.top += 20;
                img.set(objectJson);
            } else if (['i-text', "IText", 'text'].includes(object.type)) {
                const { text, ...objectJson } = object.toObject();
                const textObj = await this.addText(object.text);
                objectJson.left += 20;
                objectJson.top += 20;
                textObj.set(objectJson);
            }
        }
    }

    //删除
    del() {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            Taro.showModal({
                title: "删除", // 标题
                content: "是否要删除", // 内容
                showCancel: true, // 不显示取消按钮（设为 true 则显示两个按钮）
                confirmText: "确定", // 确认按钮文字
                success: (res) => {
                    if (res.confirm) {
                        this.discardActiveObject();
                        this.remove(activeObject);
                        this.recordHistory();
                        this.requestRenderAll(); // 必须重新渲染
                    }
                }
            });
        }
    }
    // 上下翻转
    flipY(): void {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            activeObject.flipY = !activeObject.flipY;
            designerRender.recordHistory();
            this.requestRenderAll();
        }
    }

    //左右翻转
    flipX(): void {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            activeObject.flipX = !activeObject.flipX;
            designerRender.recordHistory();
            this.requestRenderAll();
        }
    }

    //替换图片
    async replaceImg(url?: string): Promise<void> {

        const newSrc = url || await new Promise(async (resolve) => {
            const chooseImage = await utils.selectFile();
            if (chooseImage.tempFilePaths[0]) {
                // utilsApi不存在，注释掉相关调用
                // const url = await utilsApi.uploadOss(chooseImage.tempFilePaths[0], Api.ossDirectory);
                // 直接使用本地路径作为模拟返回值
                resolve(chooseImage.tempFilePaths[0]);
            }
        });

        const activeObject = this.getActiveObject();
        if (activeObject && activeObject.type === 'image') {
            const img = await this.createImage(newSrc!);
            const originWdith = activeObject.getScaledWidth();
            const originHeight = activeObject.getScaledHeight();
            const { width, height } = img;
            const minScale = Math.min(originWdith / width, originHeight / height);
            activeObject.set({
                src: newSrc,
                width,
                height,
                scaleX: minScale,
                scaleY: minScale,
                _element: img,
            });
            activeObject.setCoords();
            await designerRender.requestRenderAll();
            designerRender.recordHistory();
        }
    }
    // 通用抠图
    async normalMatting() {
        const object = this.getActiveObject();
        if (object && object.type === 'image') {
            Taro.showLoading({
                title: '抠图中...',
                mask: false,
            });
            let url = object.src;
            url = utils.ossSuffix(url);

            // utilsApi不存在，注释掉相关调用
            // url = await utilsApi.commonCutImage(url);
            // 模拟跳过处理，直接使用原URL
            Taro.downloadFile({
                url: url,
                success: async (res) => {
                    if (res.statusCode === 200) {
                        // let ossUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
                        // console.log('ossUrl', ossUrl);
                        // 直接使用本地路径
                        await this.replaceImg(utils.ossSuffix(res.tempFilePath, 1024));
                        Taro.hideLoading();
                    }
                },
                fail: (err) => {
                    Taro.showToast({
                        title: `E:${url}`,
                        icon: 'none',
                    });
                }
            });
        }
    }

    //抠人像
    async matting() {
        const object = this.getActiveObject();
        if (object && object.type === 'image') {
            Taro.showLoading({
                title: '抠图中...',
                mask: false,
            });
            let url = object.src;
            url = utils.ossSuffix(url);

            // utilsApi不存在，注释掉相关调用
            // url = await utilsApi.humanBodySeg(url);
            // 模拟跳过处理，直接使用原URL
            Taro.downloadFile({
                url: url,
                success: async (res) => {
                    if (res.statusCode === 200) {
                        // let ossUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
                        // console.log('ossUrl', ossUrl);
                        // 直接使用本地路径
                        await this.replaceImg(utils.ossSuffix(res.tempFilePath, 1024, false));
                        Taro.hideLoading();
                    }
                },
                fail: (err) => {
                    Taro.showToast({
                        title: `E:${url}`,
                        icon: 'none',
                    });
                }
            });

        }
    }

    // 抠头像
    async fastener() {
        const object = this.getActiveObject();
        if (object && object.type === 'image') {
            Taro.showLoading({
                title: '抠图中...',
                mask: false,
            });
            let url = object.src;
            url = utils.ossSuffix(url);

            // utilsApi不存在，注释掉相关调用
            // const imageUrls = await utilsApi.iconSeg(url);
            // 模拟返回空数组
            const imageUrls = [];

            await Promise.all(
                imageUrls.map(async (item) => {
                    return new Promise<void>((resolve, reject) => {
                        Taro.downloadFile({
                            url: item,
                            success: async (res) => {
                                if (res.statusCode === 200) {
                                    // let ossUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
                                    // console.log('ossUrl', ossUrl);
                                    // 直接使用本地路径
                                    await this.addImg(utils.ossSuffix(res.tempFilePath, 1024, false));
                                    resolve();
                                }
                            },
                            fail: (err) => {
                                // reject(err);
                                resolve();
                            }
                        });
                    });
                })
            );

            // 删除原图
            this.remove(object);

            // Taro.downloadFile({
            //     url: url,
            //     success: async (res) => {
            //         if (res.statusCode === 200) {
            //             let ossUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
            //             console.log('ossUrl', ossUrl);
            //             await this.replaceImg(utils.ossSuffix(ossUrl, 1024, false));
            //             Taro.hideLoading();
            //         }
            //     },
            //     fail: (err) => {
            //     }
            // });

            // Taro.showToast({
            //     title: `E:${url}`,
            //     icon: 'none',
            // });
        }
    }

    //人像动漫化
    async anime() {

        const object = this.getActiveObject();
        if (object && object.type === 'image') {
            Taro.showLoading({
                title: 'AI生图...',
                mask: false,
            });
            let url = object.src;
            url = utils.ossSuffix(url);

            // utilsApi不存在，注释掉相关调用
            // url = await utilsApi.humanAnimeStyle(url);
            // 模拟跳过处理，直接使用原URL
            // 处理返回的图片 URL
            Taro.downloadFile({
                url: url,
                success: async (res) => {
                    if (res.statusCode === 200) {
                        // const uploadedUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
                        // console.log('上传后的 URL:', uploadedUrl);
                        // 直接使用本地路径
                        const ossUrl = utils.ossSuffix(res.tempFilePath, 1024, false);
                        await this.replaceImg(ossUrl);
                        Taro.hideLoading();
                    }
                },
                fail: (err) => {
                    Taro.showToast({
                        title: `E:${url}`,
                        icon: 'none',
                    });
                }
            });
        }
    }

    // 图片变高清
    async highDefinition() {


        const object = this.getActiveObject();
        if (object && object.type === 'image') {
            const message = await new Promise<string>((resolve, reject) => {
                let url = object.src;
                url = utils.ossSuffix(url);
                // 高清化服务
                const match = url.match(/(\d+)_(\d+)_/);

                if (match) {
                    const width = match[1];
                    const height = match[2];
                    if ((width > 0 && width < 2048) || (height > 0 && height < 2048)) {
                        Taro.showLoading({
                            title: '变高清...',
                            mask: false,
                        });

                        Taro.hideLoading();
                        resolve("处理完成");
                        return;
                    }
                }
                resolve("图片无需优化");
            });

            if (message) {
                Taro.showToast({
                    title: message,
                    mask: false,
                });
            }
        }
    }

    //选中上一个
    async selectPrev() {
        const objects = this.getObjects();
        if (objects.length > 0) {
            const activeObject = this.getActiveObject();
            const indexof = Math.max(objects.indexOf(activeObject), 0);
            const newIndex = (indexof - 1 + objects.length) % objects.length;
            this.setActiveObject(objects[newIndex]);
            this.requestRenderAll();
        }
    }

    //选中下一个
    async selectNext() {
        const objects = this.getObjects();
        if (objects.length > 0) {
            const activeObject = this.getActiveObject();
            const indexof = Math.max(objects.indexOf(activeObject), 0);
            const newIndex = (indexof + 1) % objects.length;
            this.setActiveObject(objects[newIndex]);
            this.requestRenderAll();
        }
    }

    //获取计算好的打印区域的宽高和位置
    async get_print_area() {
        const { activeComponent, goodsBaseData, goodsBaseDataComponents } = designerStore;
        if (goodsBaseData) {
            const component = goodsBaseData.data.components.find((c) => c.key === activeComponent);
            if (component) {
                const { print_area_height, print_area_left, print_area_top, print_area_width, key } = component;
                const size = await goodsUtils.computerComponentSize(goodsBaseData, key); // 计算组件尺寸
                const width = size.width * (1 / 2.8346);
                const height = size.height * (1 / 2.8346);
                const sideLength = Math.max(size.width, size.height) * (1 / 2.8346);
                // 计算打印区域的宽高和位置
                if (goodsBaseData.secondaryCraftName === "升华") {
                    // 升华
                    return {
                        left: ((sideLength - width) / 2 * 1024) / sideLength,
                        top: ((sideLength - height) / 2 * 1024) / sideLength,
                        width: (width * 1024) / sideLength,
                        height: (height * 1024) / sideLength,
                        print_area_height,
                        print_area_left,
                        print_area_top,
                        print_area_width,
                        sideLength
                    };
                } else if (["直喷", "烫画"].includes(goodsBaseData.secondaryCraftName)) {
                    // "直喷", "烫画"
                    return {
                        left: (print_area_left * 1024) / sideLength,
                        top: (print_area_top * 1024) / sideLength,
                        width: (print_area_width * 1024) / sideLength,
                        height: (print_area_height * 1024) / sideLength,
                        print_area_height,
                        print_area_left,
                        print_area_top,
                        print_area_width,
                        sideLength
                    };
                }
            }
        }

        return {
            left: 0,
            top: 0,
            width: 1024,
            height: 1024,
            print_area_height: 1024,
            print_area_left: 0,
            print_area_top: 0,
            print_area_width: 1024,
            sideLength: 1024
        };
    }
    //设置当前对象的对齐方式
    // | 'leftTop'
    // | 'top'
    // | 'rightTop'
    // | 'left'
    // | 'center'
    // | 'right'
    // | 'leftBottom'
    // | 'bottom'
    // | 'rightbottom',
    async setObjectAilgn(ailgnType: string): Promise<void> {



        const activeObject = this.getActiveObject();
        if (!activeObject) {
            return;
        }
        // 计算打印区域
        const { left, top, width, height } = await this.get_print_area();

        //计算对象的尺寸
        const objectWightHalf = activeObject.getScaledWidth() / 2;
        const objectHeightHalf = activeObject.getScaledHeight() / 2;
        const widthHalf = width / 2;
        const heightHalf = height / 2;

        switch (ailgnType) {
            case 'leftTop':
                activeObject.set({ left: objectWightHalf + left, top: objectHeightHalf + top });
                break;
            case 'top':
                activeObject.set({ left: widthHalf + left, top: objectHeightHalf + top });
                break;
            case 'rightTop':
                activeObject.set({ left: width - objectWightHalf + left, top: objectHeightHalf + top });
                break;
            case 'left':
                activeObject.set({ left: objectWightHalf + left, top: heightHalf + top });
                break;
            case 'center':
                activeObject.set({ left: widthHalf + left, top: heightHalf + top });
                break;
            case 'right':
                activeObject.set({ left: width - objectWightHalf + left, top: heightHalf + top });
                break;
            case 'leftBottom':
                activeObject.set({ left: objectWightHalf + left, top: height - objectHeightHalf + top });
                break;
            case 'bottom':
                activeObject.set({ left: widthHalf + left, top: height - objectHeightHalf + top });
                break;
            case 'rightbottom':
                activeObject.set({
                    left: width - objectWightHalf + left,
                    top: height - objectHeightHalf + top,
                });
                break;
        }

        activeObject.setCoords();
        this.requestRenderAll();
    }

    // 水平对齐
    async horizontalAlign() {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            const { left, top, width, height } = await this.get_print_area();
            // 设置缩放值
            activeObject.set({ left: left + (width / 2) });
            this.requestRenderAll();
        }
    }

    // 垂直对齐
    async verticalAlign() {
        const activeObject = this.getActiveObject();
        if (activeObject) {
            const { left, top, width, height } = await this.get_print_area();
            activeObject.set({ top: top + height / 2 });
            this.requestRenderAll();
        }
    }

    // 加载数据
    async loadFromJSON(json: FabricJSON, clear: boolean = true): Promise<void> {
        await super.loadFromJSON(json, clear);
        this.recordHistory();
    }

    // 加载模版(时间比较久需要加载状态)
    async loadTemplate(json: FabricJSON) {
        const cloneJSON = cloneDeep(json);

        while (!this.canvas) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        Taro.showLoading({
            title: "加载中..."
        });
        // this.clear();
        // this.background = cloneJSON.background;

        // 根据打印位置计算模版元素的偏移量
        let offsetLeft = 0;
        let offsetTop = 0;
        let offsetScale = 1;
        // 获取设计区域
        const {
            left, top, width, height,
            print_area_width,
            print_area_height,
            print_area_left,
            print_area_top,
            sideLength
        } = await this.get_print_area();

        const { goodsBaseData } = designerStore;

        if (goodsBaseData.secondaryCraftName === "升华") {
            let offsetScale = Math.min(512 / 400, 512 / 530);
            cloneJSON.objects.map((o: any) => {
                o.left! = o.left! * offsetScale + 256 + 512 / 2 - 200 * offsetScale;
                o.top! = o.top! * offsetScale + 256 + 512 / 2 - 265 * offsetScale;
                o.scaleX! *= offsetScale;
                o.scaleY! *= offsetScale;
            });
        } else {
            let offsetScale = Math.min(width / 400, height / 530);
            cloneJSON.objects.map((o: any) => {
                o.left! = o.left! * offsetScale + left + width / 2 - 200 * offsetScale;
                o.top! = o.top! * offsetScale + top + height / 2 - 265 * offsetScale;
                o.scaleX! *= offsetScale;
                o.scaleY! *= offsetScale;
            });
        }
        await this.loadFromJSON(cloneJSON, false);
        Taro.hideLoading();
    }


    // 是否开启历史记录
    historyEnable = true;

    recordHistory() {
        if (this.historyEnable) {
            const json = this.toJSON();
            designerHistory.recordHistory(json);
        }
    }

    // 撤销操作
    async undo() {
        if (designerHistory.hasUndo) {
            this.historyEnable = false;
            const json = designerHistory.undo();
            await this.loadFromJSON(json);
            this.historyEnable = true;
        }
    }

    // 重做操作
    async redo() {
        if (designerHistory.hasRedo) {
            this.historyEnable = false;
            const json = designerHistory.redo();
            await this.loadFromJSON(json);
            this.historyEnable = true;
        }
    }

    // 全选
    selectAll() {
        this.discardActiveObject();
        //@ts-ignore
        const objects = this.getObjects().filter(obj => obj.name !== 'background');

        if (objects.length === 0) return;
        //@ts-ignore
        const aGroup = new ActiveSelection(objects.reverse(), {
            //@ts-ignore
            canvas: this,
        });
        aGroup.setControlsVisibility({
            bl: false,
            br: true,
            tl: true,
            tr: false,
            mtr: false,
            mb: false,
            ml: false,
            mr: false,
            mt: false,
        });
        aGroup.controls.br = brContorls;
        aGroup.controls.tl = tlContorls;
        set(aGroup, 'id', Date.now());
        // aGroup.controls.tr = trContorls;
        const center = aGroup.getCenterPoint();
        aGroup.originX = 'center';
        aGroup.originY = 'center';
        aGroup.left = center.x;
        aGroup.top = center.y;
        this.setActiveObject(aGroup);
        this.renderAll();
    }

}

const designerRender = new DesignerRender();

// 渲染前
designerRender.addEventListener('before:render', (ctx) => {
    const { activeComponent } = designerStore;
    if (activeComponent) {

        // 设置编辑器布片内的布料底色
        // if (designerRender.ctx) {
        //     designerRender.ctx.fillStyle = design_data.colorValue;
        //     designerRender.ctx.fillRect(0, 0, 1024, 1024);
        // }

        //绘制编辑器布片外的白色区域只保留布片内的背景颜色
        // if (fabricMark && designerRender.ctx) {
        //     fabricMark.clipOutLine(designerRender.ctx, 1024, undefined, '#ffffff', 1);
        // }
    }
});

// 渲染后更新状态
designerRender.addEventListener('after:render', () => {
    //把背景颜色和每个对象都绘制到纹理上去
    const { activeComponent } = designerStore;
    // 移除对不存在模块的引用
    // const ctx = textureManager.getCtx(activeComponent);
    // const texture = textureManager.getTexture(activeComponent);
    // const canvas = textureManager.getCanvas(activeComponent);
    // const transparentCanvas = textureManager.getTransparentCanvas(activeComponent);
    // const transparentCtx = textureManager.getTransparentCtx(activeComponent);
    // const transparentTexture = textureManager.getTransparentTexture(activeComponent);
    // 注释掉使用不存在变量的条件判断
    /*if (ctx && texture && transparentCtx && transparentTexture) {
        transparentCtx.save();
        transparentCtx.clearRect(0, 0, 1024, 1024);
        for (let obj of designerRender._objects) {
            obj.render(transparentCtx);
        }
        transparentCtx.restore();

        // 设计区域裁剪
        if (designerRender.designMark && designerRender.designMark.width) {
            transparentCtx.save();
            transparentCtx.globalCompositeOperation = "destination-out";
            transparentCtx.globalAplah = 0.5;
            transparentCtx.drawImage(designerRender.designMark, 0, 0, 1024, 1024);
            transparentCtx.restore();
        }

        // 把透明canvs上的图案绘制到透明纹理上
        ctx.clearRect(0, 0, 1024, 1024);
        // 绘制背景色
        ctx.save();
        ctx.globalCompositeOperation = "source-over";
        ctx.fillStyle = designerRender.background || "#ffffff";
        ctx.fillRect(0, 0, 1024, 1024);
        ctx.restore();
        ctx.drawImage(transparentCanvas, 0, 0, 1024, 1024);

        texture.needsUpdate = true;
        transparentTexture.needsUpdate = true;
    }
    */

    // 绘制到画布上的canvas上面
    if (designerRender.canvasCtx) {
        designerRender.canvasCtx.clearRect(0, 0, 1024, 1024);
        designerRender.canvasCtx.drawImage(designerRender.mainCanvas, 0, 0, 1024, 1024);
    }

    // perview3der.requestRender();
    //保存数据到store中
    // 移除对不存在模块的引用
    if (!designerStore.loadding && !designerStore.switching) {

        designerStore.modifyDesignData(designerRender.toJSON());
    }

    //维护是否有对象的状态
    designerStore.setHasObject(designerRender._objects.length > 0);

});

// 画布上有对象被选中时
designerRender.addEventListener('selection:created', (e) => {
    // const activeObject = get(e, ['selected', 0], undefined);
    const activeObject = designerRender.getActiveObject();
    //名字加号码在第三步时不可选中
    // if (nameNumStore.step === 3) {
    //     if (activeObject && ['name', 'num'].includes(activeObject.name || '')) {
    //         this.discardActiveObject();
    //         return;
    //     }
    // }
    if (activeObject) {
        designerStore.setActiveObjectId(activeObject.id);
        designerStore.setRotation(activeObject.angle || 0);
        designerStore.setLock(!!activeObject.lockMovementX);

        switch (activeObject.type) {
            case 'image':
            case 'Image':
                designerStore.setActiveObjectType('image');
                designerStore.setRepeat(activeObject.repeat);
                designerStore.setRepeatSpaceX(activeObject.repeatSpaceX);
                designerStore.setRepeatSpaceY(activeObject.repeatSpaceY);
                designerStore.setRepeatSpacelink(
                    activeObject.repeatSpaceX ===
                    activeObject.repeatSpaceY,
                );
                designerStore.setClipSvgUrl(activeObject.clipSvgUrl);
                break;

            case 'i-text':
            case 'Text':
            case 'text':
                designerStore.setActiveObjectType('text');
                designerStore.setFontFamily(activeObject.fontFamily);
                designerStore.setFontSize(activeObject.fontSize || 20);
                designerStore.setFontSpace(activeObject.charSpacing || 0);
                designerStore.setLineHeight(activeObject.lineHeight || 0);
                designerStore.setBendDegree(activeObject.bendDegree || 0);

                const {
                    text,// 文本
                    stroke,// 描边颜色
                    strokeWidth,// 描边
                    charSpacing,// 间距
                    lineHeight,// 行高
                    bendDegree,// 弯曲角度
                    color,// 颜色
                    fontFamily,// 字体
                    underline,// 下划线
                    fontWeight,// 粗体
                    fontStyle, // 斜体
                    direction,// 方向
                    textAlign,// 文字对齐方式
                    scaleX,
                    scaleY,
                    fontSize,
                } = activeObject;

                // 移除对不存在模块的引用
                // textModelStore.set({
                //     // show: true,
                //     text,// 文本
                //     fontWeight,// 加粗
                //     fontStyle, // 斜体
                //     direction,// 方向
                //     textAlign,// 文字对齐方式
                //     stroke,// 描边颜色
                //     strokeWidth,// 描边
                //     charSpacing,// 间距
                //     lineHeight,// 行高
                //     bendDegree,// 弯曲角度
                //     color,// 颜色
                //     fontFamily,// 字体
                //     underline,// 下划线
                // });


                break;

            case 'activeselection':
                designerStore.setActiveObjectType('activeselection');

            default:
                break;
        }
    }
});

designerRender.addEventListener('selection:updated', (e) => {
    // const activeObject = get(e, ['selected', 0], undefined);

    const activeObject = designerRender.getActiveObject();

    //名字加号码在第三步时不可选中
    // if (nameNumStore.step === 3) {
    //     if (activeObject && ['name', 'num'].includes(activeObject.name || '')) {
    //         this.discardActiveObject();
    //         return;
    //     }
    // }

    if (activeObject) {
        designerStore.setActiveObjectId(activeObject.id);
        // designerStore.setRotation(activeObject.angle || 0);
        // designerStore.setLock(!!activeObject.lockMovementX);

        switch (activeObject.type) {
            case 'image':
            case 'Image':
                designerStore.setActiveObjectType('image');
                // designerStore.setRepeat(activeObject.repeat);
                // designerStore.setRepeatSpaceX(activeObject.repeatSpaceX);
                // designerStore.setRepeatSpaceY(activeObject.repeatSpaceY);
                // designerStore.setRepeatSpacelink(
                //     activeObject.repeatSpaceX ===
                //     activeObject.repeatSpaceY,
                // );
                // designerStore.setClipSvgUrl(activeObject.clipSvgUrl);
                break;

            case 'i-text':
            case 'Text':
            case 'text':
                designerStore.setActiveObjectType('text');
                // designerStore.setFontFamily(activeObject.fontFamily);
                // designerStore.setFontSize(activeObject.fontSize || 20);
                // designerStore.setFontSpace(activeObject.charSpacing || 0);
                // designerStore.setLineHeight(activeObject.lineHeight || 0);
                // designerStore.setBendDegree(activeObject.bendDegree || 0);

                const {
                    text,// 文本
                    stroke,// 描边颜色
                    strokeWidth,// 描边
                    charSpacing,// 间距
                    lineHeight,// 行高
                    bendDegree,// 弯曲角度
                    color,// 颜色
                    fontFamily,// 字体
                    underline,// 下划线
                    fontWeight,// 粗体
                    fontStyle, // 斜体
                    direction,// 方向
                    textAlign,// 文字对齐方式
                } = activeObject;

                // 移除对不存在模块的引用
                // textModelStore.set({
                //     // show: true,
                //     text,// 文本
                //     fontWeight,// 加粗
                //     fontStyle, // 斜体
                //     direction,// 方向
                //     textAlign,// 文字对齐方式
                //     stroke,// 描边颜色
                //     strokeWidth,// 描边
                //     charSpacing,// 间距
                //     lineHeight,// 行高
                //     bendDegree,// 弯曲角度
                //     color,// 颜色
                //     fontFamily,// 字体
                //     underline,// 下划线
                // });

                break;

            case 'activeselection':
                designerStore.setActiveObjectType('activeselection');

            default:
                break;
        }


    }
});

designerRender.addEventListener('selection:cleared', (e) => {
    designerStore.setActiveObjectId('');
    // designerStore.setActiveObjectType('');
});

designerRender.addEventListener('object:modified', async (e) => {
    const activeObject = designerRender.getActiveObject();

    // 专注模式
    // const { focusMode } = designerStore;
    // if (activeObject && focusMode) {
    //     const scaleWdith = activeObject.getScaledWidth();
    //     const scaleHeight = activeObject.getScaledHeight();
    //     const maxSide = Math.max(scaleWdith, scaleHeight);
    //     const left = activeObject.left;
    //     const top = activeObject.top;
    //     const scale = 1024 / (maxSide * 2); //clamp(1024 / (maxSide * 2), 1, 10);
    //     designerRender.viewTransition.set({
    //         scale: scale,
    //         x: (maxSide - left) * scale,
    //         y: (maxSide - top) * scale
    //     });
    // } else {
    //     designerRender.viewTransition.set({ scale: 1, x: 0, y: 0 });
    // }

    //判断图片对象是否模糊
    // if (["image", "Image"].includes(activeObject.type)) {
    //     const isBlur = await activeObject.isBlur();
    //     if (isBlur) {
    //         blurWarnStore.show();
    //     }
    //     console.log('isBlur', isBlur);
    // }

    // 历史记录
    designerRender.recordHistory();
});

// 监听对象的移动然后做居中吸附计算
designerRender.addEventListener('object:moving', async (e) => {
    const activeObject = designerRender.getActiveObject();
    const threshold = 20; // 像素阈值
    if (activeObject) {
        const ract = await designerRender.get_print_area();
        const { left, top, width, height } = ract;
        if (Math.abs(activeObject.left - (left + (width / 2))) < threshold) {
            // 如果距离中心点小于阈值则吸附到中心点
            activeObject.set({ left: left + (width / 2) });
        }
        if (Math.abs(activeObject.top - (top + (height / 2))) < threshold) {
            // 如果距离中心点小于阈值则吸附到中心点
            activeObject.set({ top: top + (height / 2) });
        }
    }
});

// 监听选中部位的变化 以及底板的变化
const dispose = autorun(async () => {
    // console.log("监听选中部位的变化 以及底板的变化", new Date().valueOf());
    const { activeComponent, goodsBaseDataComponents, goodsBaseData } = designerStore;
    designerStore.setLoadingMask(true);

    const designData = designerStore.getCurretntDesignData();
    await new Promise(resolve => requestAnimationFrame(resolve));
    if (activeComponent) {
        // 加载设计数据
        const componentDesignData = designData.designData[activeComponent];

        // 更新纹理对应的数据
        if (componentDesignData) {
            designerHistory.resetHistory();

            await designerRender.loadFromJSON(componentDesignData);

            // 提取文本和图片对象
            const objects = designerRender.getObjects();
            const texts = objects.filter(obj => ["text", "IText", "i-text"].includes(obj.type) && obj["canReplace"]);
            const imgs = objects.filter(obj => ["Image", "image"].includes(obj.type) && obj["canReplace"]);

            indexStore.setTexts(texts.map((item: any) => ({
                id: item.id,
                text: item.text,
            })));

            indexStore.setImgs(imgs.map((item: any) => ({
                id: item.id,
                url: item.src,
            })));

        }

        for (let component of goodsBaseDataComponents) {
            let { designMark, oulineMark, outlineDash, printlineDash } = component;
            // 处理升华的情况
            if (goodsBaseData && ["烫画", "直喷"].includes(goodsBaseData.secondaryCraftName)) {
                outlineDash = "";
            }
            if (component.key === activeComponent) {
                // 设置遮罩图
                await designerRender.initFabricMarkMap(designMark, oulineMark, outlineDash, printlineDash);
            } else {

                // 把这些图片都下载到本地并且缓存起来

            }
        }

        // if (!loadding) {
        //清理历史记录
        // designerHistory.resetHistory();
        // }
        await new Promise(resolve => setTimeout(resolve, 100));
        designerStore.setSwitching(false);
        designerStore.setLoadingMask(false);

    }

    designerStore.setLoadding(false);
}, { delay: 200 });

const dispose1 = autorun(async () => {
    const { activeComponent, goodsBaseData, selectColorValue, loadding } = designerStore;
    // 如果是局部印的话有衣服背景图

    // 加载中的时候就不往下执行了
    if (loadding) {
        return;
    }

    if (goodsBaseData && ["直喷", "烫画"].includes(goodsBaseData.secondaryCraftName)) {
        const { colors } = goodsBaseData.data;
        const currentColor = colors.find((c) => c.color === selectColorValue);
        designerRender.background = undefined;
        if (currentColor) {
            if (activeComponent === "front") {
                await designerRender.setBackgroundImage(currentColor.frontImg);
            } else if (activeComponent === "back") {
                await designerRender.setBackgroundImage(currentColor.backImg);
            }
        }
        designerRender.requestRenderAll();
    } else if (goodsBaseData && ["升华"].includes(goodsBaseData.secondaryCraftName)) {
        await designerRender.setBackgroundImage("");
        designerRender.background = selectColorValue;
    }

}, { delay: 30 });

//数据有更新时就触发一次渲染
const dispose2 = autorun(() => {
    const { needUpdateTime } = designerStore;
    if (needUpdateTime > 0) {
        designerRender.requestRenderAll();
    }
}, { delay: 30 });

//暂停专注模式
// const dispose2 = autorun(() => {
//     const { activeObjectType, focusMode, activeObjectId } = designerStore;

//     if (activeObjectType && activeObjectId && focusMode) {
//         const activeObject = designerRender.getActiveObject();
//         const scaleWdith = activeObject.getScaledWidth();
//         const scaleHeight = activeObject.getScaledHeight();
//         const maxSide = Math.max(scaleWdith, scaleHeight);
//         const left = activeObject.left;
//         const top = activeObject.top;
//         const scale = 1024 / (maxSide * 2); //clamp(1024 / (maxSide * 2), 1, 10);
//         designerRender.viewTransition.set({
//             scale: scale,
//             x: (maxSide - left) * scale,
//             y: (maxSide - top) * scale
//         });
//     } else {
//         designerRender.viewTransition.set({ scale: 1, x: 0, y: 0 });
//     }
// }, { delay: 30 });

// 监听画布放大的状态
const dispose3 = autorun(async () => {
    const { amplify, goodsBaseData } = designerStore;
    if (amplify && ["烫画", "直喷"].includes(goodsBaseData.secondaryCraftName)) {
        const ract = await designerRender.get_print_area();
        const maxSide = Math.max(ract.width, ract.height) + 10;
        const left = ract.left;
        const top = ract.top;
        const scale = 1024 / (maxSide);
        designerRender.viewTransition.set({
            scale: scale,
            x: ((maxSide - ract.width) / 2 - left) * scale,
            y: ((maxSide - ract.height) / 2 - top) * scale
        });

    } else {
        designerRender.viewTransition.set({ scale: 1, x: 0, y: 0 });
    }

});


export default designerRender;